<template>
  <div class="salary_rostering">
    <div class="select">
      <el-form :inline="true">
        <el-form-item label="年月">
          <el-date-picker size="small"
                          v-model="yearMonth"
                          @change="getFinSalaryRosteringData"
                          type="month"
                          placeholder="选择月"
                          :clearable="false"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="dateChange" size="small" type="primary">
            排班
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row>
      <el-table :data="tableData" :header-cell-style="{'text-align':'center'}" height="75vh">
        <el-table-column prop="groupName" label="考勤组" min-width="150" fixed="left">
        </el-table-column>
        <el-table-column label="每日详情" key="年">
              <span slot="header" style="float: left!important;">
                每日详情
              </span>
          <el-table-column v-for="(item,index) in months" :key='item.date' :label="item.date+'('+item.day +')'"
                           min-width="120">
            <template slot-scope="scope">
              <el-tag style="width: 80%;text-align: center!important;" @click="edit(item,scope.row)"
                      :type="getObjectProperty(scope.row.list,item.date)==='正班'?'success':getObjectProperty(scope.row.list,item.date)==='休息'?'info':'danger'">
                {{ getObjectProperty(scope.row.list, item.date) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-calendar>
        <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
        <template
            slot="dateCell"
            slot-scope="{date, data}">
          <p :class="data.isSelected ? 'is-selected' : ''">
<!--            {{ data.day.split('-').slice(1).join('-') }} {{ data.isSelected ? '✔️' : ''}}-->
            <el-radio v-model="item.groupName" :label="item.groupName" v-for="item in tableData"></el-radio>
          </p>
        </template>
      </el-calendar>
    </el-row>
    <el-drawer
        :modal="false"
        style="overflow-x:hidden!important;"
        size="50%"
        :title="title"
        :visible.sync="addDrawer"
        direction="rtl">
      <div slot="title">
        <h2 v-text="title"></h2>
      </div>
      <el-form :model="form" style="padding-right: 0.5rem;overflow-x:hidden!important;">
        <el-form-item label="考勤组" :label-width="formLabelWidth">
          <el-select v-model="form.group" placeholder="请选择" value-key="id" class="w100" @change="typeChange" size="small"
                     >
            <el-option
                v-for="item in groupList"
                :key="item.id"
                :label="item.groupName+'('+item.salaryRosteringClass+')'"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排班日期" :label-width="formLabelWidth" v-if="form.group" @change="typeChange">
          <el-radio-group v-model="form.type" :disabled="isEdit" size="small" >
            <!--            <el-radio :label="1">系统正班排班({{ form.group.salaryRosteringClass }})</el-radio>-->
            <el-radio :label="2">自定义排班</el-radio>
            <el-radio :label="3">系统休息排班</el-radio>
            <!--            <el-radio :label="4">周末排班</el-radio>-->
            <el-radio :label="5">系统默认排班({{ form.group.salaryRosteringClass + '正班，其他星期数休息' }})</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="本月日期" :label-width="formLabelWidth" v-if="monthDate.length>0&&form.type===2">

          <el-checkbox-group v-model="dateList" size="small" >
            <el-col v-for="item in monthDate" :span="6" :key="item.rosteringDate">
              <el-checkbox :label="item">{{ item.rosteringDate }} ({{
                  item.rosteringDate|formatDateDDDD
                }})
              </el-checkbox>
            </el-col>
          </el-checkbox-group>

        </el-form-item>
        <el-form-item label="选择日期" :label-width="formLabelWidth" v-if="dateList.length>0">
          <el-col :span="6" v-for="(item,index) in dateList" :key="item.rosteringDate">
            <el-tag :type="item.type==='正班'?'success':'danger'" closable @close="deleteDate(item,index)"
                    v-if="form.rosteringType===null">{{ item.rosteringDate }}
              ({{ item.rosteringDate|formatDateDDDD }}) {{ item.type }}
            </el-tag>
            <el-tag :type="form.rosteringType==='正班'?'success':'danger'" closable @close="deleteDate(item,index)"
                    v-else>{{ item.rosteringDate }}
              ({{ item.rosteringDate|formatDateDDDD }}) {{ form.rosteringType }}
            </el-tag>
          </el-col>
          <el-tag class="w100">合计天数：<b>{{ dateList.length }}</b>天</el-tag>
        </el-form-item>
        <el-form-item label="排班类别" :label-width="formLabelWidth"
                      v-if="(dateList.length>0&&form.type<5)||(dateList.length>0&&isEdit)">
          <el-radio-group v-model="form.rosteringType">
            <el-radio label="正班">正班</el-radio>
            <el-radio label="周末">周末</el-radio>
            <el-radio label="休息">休息</el-radio>
            <el-radio label="法假">法假</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="footer" style="position: absolute;bottom:1rem;right: 1rem;">
          <el-button @click="closeDrawer" size="small" >取消</el-button>

          <el-button type="primary" :loading="isLoading" @click="addBatchSalaryRostering" size="small"
                     style="padding-left: 2rem;padding-right: 2rem;" :disabled="isEdit&&form.rosteringType===null"><span
              v-text="isLoading?'加载中...':'确认'"></span>
          </el-button>
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import moment from "moment";

export default {
  name: "SalaryRostering",
  data() {
    return {
      yearMonth: moment(new Date()).format("YYYY-MM-DD"),
      groupList: [],
      tableData: [],
      addDrawer: false,
      title: "",
      day: moment().days(),
      formLabelWidth: "120px",
      form: {
        group: null,
        rosteringDate: null,
        rosteringType: null,
        weekDate: null
      },
      dateList: [],
      monthDate: [],
      months: [],
      statutoryLeave: [],
      isLoading: false,
      isEdit: false,
    }
  },
  created() {
    this.getGroupList()
    this.months = []
    this.months = this.$tools.getMonthData(this.yearMonth)
    console.log("MOnths:", this.months.length)
    this.getFinSalaryRosteringData()
  },
  watch: {
    'form.type': {
      handler(newVal, oldVal) {
        this.typeChange()
      }
    }
  },
  methods: {
    edit(item, group) {
      this.isEdit = true
      this.form.group = group
      let time = item.year + '-' + item.date
      this.title = moment(time).format("YYYY年MM月DD日") + "排班编辑"
      this.form.type = 2
      this.dateList = []
      this.dateList.push(
          {
            rosteringDate: moment(time).format("YYYY-MM-DD"),
            week: moment(time).format("E"),
            type: ""
          }
      )
      this.addDrawer = true
      console.log("时间：", time)
    },
    getObjectProperty(list, date) {
      let s
      list.find(obj => {
        if (obj.date === date) {
          s = obj.data.rosteringType
        }
      })
      if (s === undefined) {
        s = '暂无排班'
      }
      return s

    },
    closeDrawer() {
      this.addDrawer = false
      this.dateList = []
      this.monthDate = []
      this.isEdit = false
      this.form.rosteringType = null
    },
    dateChange() {
      this.getFinStatutoryLeave1()
      this.isEdit = false
      this.getGroupList()
      this.getFinSalaryRosteringData()
      this.title = moment(this.yearMonth).format("YYYY年MM月") + "批量排班"
      this.addDrawer = true
    },
    showS() {
      this.getWeekIndex(this.form.group.salaryRosteringClass)
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.form = {}
            this.dateList = []
            done();
          })
          .catch(_ => {
          });
    },
    typeChange() {
      switch (this.form.type) {
        case 1:
          this.monthDate = []
          this.dateList = []
          this.form.rosteringType = "正班"
          this.showS()
          break;
        case 2:
          this.form.rosteringType = null
          this.monthDate = []
          this.dateList = []
          this.monthDate = this.$tools.getMonthAllDate(this.yearMonth)
          console.log(this.monthDate)
          break;
        case 3:
          this.form.rosteringType = "休息"
          this.showS()
          this.monthDate = this.$tools.getMonthAllDate(this.yearMonth)
          let list = []
          this.monthDate.forEach(item => {
            let result = this.dateList.some(obj =>
                obj.rosteringDate === item.rosteringDate
            )
            if (!result) {
              list.push(item)
            }
          })
          this.dateList = list
          break;
        case 4:

          break;
        case 5:
          this.form.rosteringType = null
          this.monthDate = this.$tools.getMonthAllDate(this.yearMonth)
          this.getWeekIndex(this.form.group.salaryRosteringClass)
          break;
      }
    },
    async getGroupList() {
      axios.get("/ding_attendance_group/list").then(res => {
        this.groupList = res.data.data
      })
    },
    getWeekIndex(data) {
      let weeks = data.split("到")
      let year = moment(this.yearMonth).year()
      let month = moment(this.yearMonth).month()
      this.dateList = []
      if (weeks.length > 0) {
        let weekNum = this.getWeekNum(weeks)
        let start = weekNum.start
        let end = weekNum.end
        let d = []
        let list = []
        for (start; start <= end; start++) {
          d = this.getDatesInWeekOfMonth(year, month, start)
          d.forEach(item => {
            list.push(moment(item).format("YYYY-MM-DD"))
          })
        }
        list.sort()
        list.forEach(item => {
          let week = moment(item).format("E")
          if (week < 6) {
            this.dateList.push({
              rosteringDate: moment(item).format("YYYY-MM-DD"),
              week: moment(item).format("E"),
              type: "正班"
            })
          } else {
            this.dateList.push({
              rosteringDate: moment(item).format("YYYY-MM-DD"),
              week: moment(item).format("E"),
              type: "周末"
            })
          }
        })

        if (this.form.type > 4) {
          let list1 = []
          this.monthDate.forEach(item => {
            let result = this.dateList.some(obj =>
                obj.rosteringDate === item.rosteringDate
            )
            if (!result) {
              list1.push(item)
            }
          })

          list1.forEach(item => {
            this.dateList.push({
              rosteringDate: moment(item.rosteringDate).format("YYYY-MM-DD"),
              week: moment(item.week).format("E"),
              type: "休息"
            })
          })
        }

        if (this.statutoryLeave.length > 0) {
          this.dateList.forEach(item => {
            let result = this.statutoryLeave.some(obj =>
                moment(obj.leaveDate).format("YYYY-MM-DD") === moment(item.rosteringDate).format("YYYY-MM-DD"))
            if (result) {
              item.type = "法假"
            }
          })
        }
        console.log("DataList:", this.dateList)
      }
    },
    getWeekDay(data) {
      let weeks = data.split("到")
      console.log(weeks)
      let year = moment(this.yearMonth).year()
      let month = moment(this.yearMonth).month()
      this.dateList = []
      if (weeks.length > 0) {
        let weekNum = this.getWeekNum(weeks)
        let start = weekNum.start
        let end = weekNum.end
        let d = []
        let list = []
        for (start; start <= end; start++) {
          d = this.getDatesInWeekOfMonth(year, month, start)
          d.forEach(item => {
            list.push(moment(item).format("YYYY-MM-DD"))
          })
        }
        list.sort()
        list.forEach(item => {
          this.dateList.push({
            rosteringDate: moment(item).format("YYYY-MM-DD"),
            week: moment(item).format("E"),
            type: "正班"
          })
        })

      }
    },
    getWeekNum(week) {
      let start = {
        "周一": 1,
        "周二": 2,
        "周三": 3,
        "周五四": 4,
        "周五": 5,
        "周六": 6,
        "周七": 7,
      }[week[0]]
      let end = {
        "周一": 1,
        "周二": 2,
        "周三": 3,
        "周五四": 4,
        "周五": 5,
        "周六": 6,
        "周七": 7,
      }[week[1]]
      return {
        start, end
      }
    },
    getDatesInWeekOfMonth(year, month, targetWeekday) {
      const dates = [];
      const firstDay = new Date(year, month, 1);
      const lastDay = new Date(year, month + 1, 0);
      for (let date = firstDay; date <= lastDay; date.setDate(date.getDate() + 1)) {
        if (date.getDay() === targetWeekday) {
          dates.push(new Date(date));
        }
      }
      return dates;
    },
    deleteDate(item, index) {
      this.dateList.splice(index, 1)
    },
    getFinStatutoryLeave() {
      axios.post("/fin_statutory_leave/list", {yearMonth: this.yearMonth}).then(res => {
        if (res.data.success) {
          console.log("法假：", res)
          this.statutoryLeave = res.data.data
        } else {
          this.statutoryLeave = []
          this.$tools.showMessageBox("当前月份暂无法假数据，是否添加？", "提示", "warning").then(confirm => {
          }).catch(cancel => {

          })
        }
      })
    },
    getFinStatutoryLeave1() {
      axios.post("/fin_statutory_leave/list", {yearMonth: this.yearMonth}).then(res => {
        if (res.data.success) {
          console.log("法假：", res)
          this.statutoryLeave = res.data.data
        } else {
          this.statutoryLeave = []
          this.$tools.showMessage("当前月份暂无法假数据", "warning")
        }
      })
    },
    addBatchSalaryRostering() {
      this.isLoading = true
      let data = []
      let type = null
      if (this.form.type < 5) {
        type = this.form.rosteringType
        this.dateList.forEach(item => {
          data.push(
              {
                id: moment(item.rosteringDate).format("YYYYMMDD") + "" + this.form.group.id,
                attendanceGroupId: this.form.group.id,
                attendanceGroupName: this.form.group.groupName,
                rosteringClass: this.form.group.salaryRosteringClass,
                rosteringDate: item.rosteringDate,
                rosteringType: type,
                weekDate: item.week,
                createTime: new Date()
              }
          )
        })
      } else {
        this.dateList.forEach(item => {
          data.push(
              {
                id: moment(item.rosteringDate).format("YYYYMMDD") + "" + this.form.group.id,
                attendanceGroupId: this.form.group.id,
                attendanceGroupName: this.form.group.groupName,
                rosteringClass: this.form.group.salaryRosteringClass,
                rosteringDate: item.rosteringDate,
                rosteringType: item.type,
                weekDate: item.week,
                createTime: new Date()
              }
          )
        })
      }
      console.log("Data:", data)
      axios.post("/fin_salary_rostering/addBatch", data).then(res => {
        if (res.data.success) {
          // this.closeDrawer()
          this.getFinSalaryRosteringData()
          this.$tools.showMessage("操作成功！", "success")
        } else {
          this.$tools.showMessage("操作失败！", "danger")
        }
      })
      this.isLoading = false
    },
    getFinSalaryRosteringData() {
      this.months = this.$tools.getMonthData(this.yearMonth)
      axios.post("/fin_salary_rostering/list", {yearMonth: this.yearMonth}).then(res => {
        console.log("Res:", res)
        if (res.data.success) {
          this.tableData = res.data.data
        }
      })
    }
  }

}
</script>

<style lang="less">
.is-selected {
  color: #1989FA;
}
.w100 {
  width: 100% !important;
}

.el-calendar__body {
  .el-calendar-table {
    .el-calendar-day {
      //height: 50px !important;
    }
  }
}
</style>
